package icu.funkye.confine.limiter.product.impl;

import java.util.concurrent.TimeUnit;
import icu.funkye.confine.common.loader.LoadLevel;
import icu.funkye.confine.limiter.product.AbstractLimiter;
import icu.funkye.confine.limiter.product.Limiter;
import com.google.common.util.concurrent.RateLimiter;

/**
 * @author jianbin.chen
 */
@LoadLevel(name = "guava")
public class GuavaLimiter extends AbstractLimiter {

    RateLimiter rateLimiter;

    @Override
    public Limiter create(String resource, int tps) {
        return create(resource, tps, 1);
    }

    @Override
    public Limiter create(String resource, int tps, long seconds) {
        currentTps = tps;
        rateLimiter = RateLimiter.create(tps);
        this.resource = resource;
        return this;
    }

    @Override
    public Limiter setTps(int tps) {
        currentTps = tps;
        rateLimiter.setRate(tps);
        return this;
    }

    @Override
    public int getTps() {
        return currentTps;
    }

    @Override
    public boolean tryAcquire(int permits, long timeout, TimeUnit unit) {
        return rateLimiter.tryAcquire(permits, timeout, unit);
    }

    @Override
    public boolean tryAcquire(int permits) {
        return tryAcquire(permits, 0, TimeUnit.MILLISECONDS);
    }

    @Override
    public boolean tryAcquire() {
        return tryAcquire(1);
    }

}
